package me.hl.pattern;

import org.junit.Test;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Planck on 2016/2/15.
 */
public class PatternDemo {

    /**
     * 匹配ip
     *
     * @param args
     */
    public static void main(String args[]) {

        Pattern pattern = Pattern.compile("^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
        while (true) {
            Scanner scanner = new Scanner(System.in);
            String str = scanner.nextLine();
            Matcher matcher = pattern.matcher(str.trim());
            //find()对字符串进行匹配,匹配到的字符串可以在任何位置.
            //matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
            if (matcher.find()) {
                System.out.println("匹配");

                //start()返回匹配到的子字符串在字符串中的索引位置.
                //end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
                //group()返回匹配到的子字符串
                System.out.println(matcher.start());
                System.out.println(matcher.end());
                System.out.println(matcher.group());
            } else {
                System.out.println("不匹配");
            }
        }
    }


    @Test
    public void patternName() {
        Pattern pattern = Pattern.compile("(?<year>\\d{4})");
        Matcher matcher = pattern.matcher("1999");
        System.out.println(matcher.find());
        System.out.println(matcher.group("year"));
    }
}
